package com.dwyinyuan.task;

import com.dwyinyuan.model.FileDTO;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.*;

public class DownloadFileTask implements Runnable {

    private static String path = "C:\\Users\\99478\\Downloads\\Music\\";
    private String src;
    private String name;

    public DownloadFileTask(FileDTO fileDTO) {
        this.src = fileDTO.getFileUrl();
        int lastIndex = src.lastIndexOf(".");
        String suffix = src.substring(lastIndex);
        this.name = fileDTO.getName() + suffix;
    }

    @Override
    public void run() {
        try {
            Connection connection = Jsoup.connect(src);
            Connection.Response response = connection
                    .method(Connection.Method.GET)
                    .ignoreContentType(true)
                    .timeout(1000000)
                    .execute();
            BufferedInputStream bufferedInputStream = response.bodyStream();
            saveFile(bufferedInputStream, path + name);
            System.out.println("download file task " + src + " 下载完成----");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    /**
     * 保存文件到本地
     */
    public static void saveFile(BufferedInputStream bufferedInputStream, String savePath) throws IOException {
        //一次最多读取1k
        byte[] buffer = new byte[1024];
        //实际读取的长度
        int readLength;
        //根据文件保存地址，创建文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
        //创建的一个写出的缓冲流
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        //文件逐步写入本地
        while ((readLength = bufferedInputStream.read(buffer, 0, 1024)) != -1) {//先读出来，保存在buffer数组中
            bufferedOutputStream.write(buffer, 0, readLength);//再从buffer中取出来保存到本地
        }
        //关闭缓冲流
        bufferedOutputStream.close();
        fileOutputStream.close();
        bufferedInputStream.close();
    }

}
